import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
// 导入组件
import Layout from '@/views/layout';
import Login from '@/views/login';
import Dashboard from '@/views/dashboard';
import Article from '@/views/article';

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    // 一级路由
    {
      path: '/',
      redirect: '/article', // 进入跟页面的时候，直接跳转到article页面
      component: Layout,
      // 二级路由
      children: [
        {
          path: '/dashboard',
          component: Dashboard
        },
        {
          path: '/article',
          component: Article
        }
      ]
    },
    {
      path: '/login',
      component: Login
    }
  ]
});
// 路由导航守卫,检查token是否过期，通过接收to,from,next三个参数控制是否放行
router.beforeEach((to, from, next) => {
  const token = store.state.user.token;
  if (to.path === '/login') {
    // 3. 如果访问的是登录页面，直接跳转到首页
    next();
  } else {
    // 4. 如果不是登录页面，直接放行
    if (token) {
      next();
    } else {
      next('/login');
    }
  }
});
export default router;
